import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';
import type { RouteLocationNormalized } from 'vue-router';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: { requiresAuth: false, title: '登录' }
    },
    // 将溯源详情页提升为顶级路由，避免嵌套问题
    {
      path: '/enterprise/traceability-detail/:id',
      name: 'traceabilityDetail',
      component: () => import('../views/enterprise/TraceabilityDetail.vue'),
      meta: { title: '溯源详情', requiresAuth: true },
      beforeEnter: (to, from, next) => {
        console.log('进入溯源详情路由, 参数:', to.params);
        next();
      }
    },
    {
      path: '/',
      component: () => import('../layout/MainLayout.vue'),
      redirect: '/dashboard',
      meta: { requiresAuth: true },
      children: [
        // 首页
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/dashboard/DashboardView.vue'),
          meta: { title: '首页', requiresAuth: true }
        },
        // 企业管理
        {
          path: 'enterprise/traceability',
          name: 'traceability',
          component: () => import('../views/enterprise/TraceabilityManagement.vue'),
          meta: { title: '溯源管理', requiresAuth: true }
        },
        {
          path: 'enterprise/info',
          name: 'enterprise-info',
          component: () => import('../views/enterprise/EnterpriseInfo.vue'),
          meta: { title: '企业信息', requiresAuth: true }
        },
        // 数据分析
        {
          path: 'analytics/overview',
          name: 'analytics-overview',
          component: () => import('../views/analytics/AnalyticsOverview.vue'),
          meta: { title: '数据概览', requiresAuth: true }
        },
        {
          path: 'analytics/reports',
          name: 'analytics-reports',
          component: () => import('../views/analytics/AnalyticsReports.vue'),
          meta: { title: '详细报告', requiresAuth: true }
        },
        // 平台运营
        {
          path: 'platform/users',
          name: 'platform-users',
          component: () => import('../views/platform/UserManagement.vue'),
          meta: { title: '用户管理', requiresAuth: true }
        },
        {
          path: 'platform/content',
          name: 'platform-content',
          component: () => import('../views/platform/ContentManagement.vue'),
          meta: { title: '内容管理', requiresAuth: true }
        },
        // 系统设置
        {
          path: 'system/basic',
          name: 'system-basic',
          component: () => import('../views/system/BasicSettings.vue'),
          meta: { title: '基础设置', requiresAuth: true }
        },
        {
          path: 'system/permissions',
          name: 'system-permissions',
          component: () => import('../views/system/PermissionsManagement.vue'),
          meta: { title: '权限管理', requiresAuth: true }
        },
        // 用户中心
        {
          path: 'profile',
          name: 'user-profile',
          component: () => import('../views/user/UserProfile.vue'),
          meta: { title: '个人信息', requiresAuth: true }
        },
        {
          path: 'change-password',
          name: 'change-password',
          component: () => import('../views/user/ChangePassword.vue'),
          meta: { title: '修改密码', requiresAuth: true }
        }
      ]
    },
    // 错误页面
    {
      path: '/404',
      name: '404',
      component: () => import('../views/error/404.vue'),
      meta: { requiresAuth: false, title: '页面未找到' }
    },
    // 匹配未定义路由，重定向到404
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ],
});

// 全局前置守卫
router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next) => {
  // 设置页面标题
  document.title = `${to.meta.title || '溯源管理系统'}`

  const userStore = useUserStore()
  
  // 不需要认证的页面直接通过
  if (!to.meta.requiresAuth) {
    // 如果已登录且访问的是登录页，则重定向到首页
    if (to.path === '/login' && userStore.isLoggedIn) {
      next({ path: '/' })
    } else {
      next()
    }
    return
  }
  
  // 检查是否已登录
  if (userStore.isLoggedIn) {
    // 已登录，但可能需要检查用户信息是否已加载
    if (!userStore.userInfo) {
      try {
        // 尝试获取用户信息
        await userStore.fetchUserInfo()
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 获取用户信息失败时清空token并跳转到登录页
        userStore.clearToken()
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
        return
      }
    }
    next()
    return
  }
  
  // 未登录，重定向到登录页
  next({
    path: '/login',
    query: { redirect: to.fullPath }
  })
})

export default router;
